package com.nobuyme.box.app;

import android.app.Application;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.widget.Toast;

import com.iflytek.cloud.SpeechConstant;
import com.iflytek.cloud.SpeechSynthesizer;
import com.iflytek.cloud.SpeechUtility;
import com.nobuyme.box.util.PollingService;
import com.nobuyme.box.util.PollingUtils;
import com.nobuyme.box.util.UICommon;
import com.nobuyme.box.util.UICommon1;
import com.tencent.bugly.crashreport.CrashReport;
import com.uuzuche.lib_zxing.DisplayUtil;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

import cn.jpush.android.api.JPushInterface;


public class MyApplication extends Application {
    public static final String BUGLY_ID ="184dc00fa7";
    public static final String PORT ="dev/ttymxc1";
    public static final String PORT2 ="dev/ttymxc2";
    public static final int TATEL =9600;
    private static SpeechSynthesizer mTts;
    private static SharedPreferences mSharedPreferences;
    // 引擎类型
    private static String mEngineType = SpeechConstant.TYPE_CLOUD;


    private static Context mAppContext = null;

    @Override
    public void onCreate() {
        super.onCreate();

        mAppContext = this.getApplicationContext();
        /**
         * 腾讯buly
         */
        initBugly();

        initJpush();
        /**
         *初始化开箱
         */
        initSerialPort();

        /**
         * 初始化尺寸工具类
         */
        initDisplayOpinion();
        /**
         * 启动轮询
         */
        startPolling();
        /**
         * 初始科大讯飞
         */
        initSpeech();
    }

    private void initJpush() {
        //初始化极光
        JPushInterface.setDebugMode(true);
        JPushInterface.init(this);
    }

    private void initSerialPort() {
//            new SerialPort(new File(PORT),TATEL,0);
//            new SerialPort(new File(PORT2),TATEL,0);
//       SerialPortController. getInstance().openSerialPort(PORT2,TATEL);

        UICommon.getInstance().setHandler(m_handler);
        UICommon.getInstance().openSeri(PORT,TATEL);
        UICommon1.getInstance().setHandler(m_handler1);
        UICommon1.getInstance().openSeri(PORT2,TATEL);

    }

    private Handler m_handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case UICommon.OPEN_SERIAL_PORT:
                    if (msg.arg1 == UICommon.CMD_SUCCESS) {
                        Toast.makeText(MyApplication.getAppContext(), "打开串口成功",Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(MyApplication.getAppContext(), "打开串口失败，信息: "+msg.obj,Toast.LENGTH_SHORT).show();
                    }
                    break;
                case UICommon.SEND_RECIVE_DATA:
                    statusDisplay(msg.arg1,msg.arg2,(String) msg.obj);
                    break;
                case UICommon.CMD_TEST_SLOT_END:
                    Toast.makeText(MyApplication.getAppContext(), "测试完毕",Toast.LENGTH_SHORT).show();
                    break;
                case UICommon.CMD_LATTICE_SET_END:
                    Toast.makeText(MyApplication.getAppContext(), "设置完毕",Toast.LENGTH_SHORT).show();
                    break;
                default:
                    break;
            }
        }
    };
    private Handler m_handler1 = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case UICommon.OPEN_SERIAL_PORT:
                    if (msg.arg1 == UICommon.CMD_SUCCESS) {
                        Toast.makeText(MyApplication.getAppContext(), "打开串口成功2",Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(MyApplication.getAppContext(), "打开串口失败，信息: "+msg.obj,Toast.LENGTH_SHORT).show();
                    }
                    break;
                case UICommon.SEND_RECIVE_DATA:
                    statusDisplay(msg.arg1,msg.arg2,(String) msg.obj);
                    break;
                case UICommon.CMD_TEST_SLOT_END:
                    Toast.makeText(MyApplication.getAppContext(), "测试完毕",Toast.LENGTH_SHORT).show();
                    break;
                case UICommon.CMD_LATTICE_SET_END:
                    Toast.makeText(MyApplication.getAppContext(), "设置完毕",Toast.LENGTH_SHORT).show();
                    break;
                default:
                    break;
            }
        }
    };
    private void statusDisplay(int iStatus ,int errCode, String msg) {
        if (UICommon.STATUS_FREE == iStatus) {
            statusDisplay(errCode,"空闲",msg);
        } else if (UICommon.STATUS_BUSY == iStatus) {
            statusDisplay(errCode,"忙碌",msg);
        } else if (UICommon.STATUS_WAIT_TAKE_GOODS == iStatus) {
            statusDisplay(errCode,"等待取货",msg);
        } else {
            statusDisplay(errCode,"未知",msg);
        }
    }

    private void statusDisplay(int errCode, String statusMsg, String msg) {
//        Toast.makeText(MyApplication.getAppContext(),msg,Toast.LENGTH_SHORT).show();
    }

    private void initBugly() {
        Context context = getApplicationContext();
        // 获取当前包名
        String packageName = context.getPackageName();
        // 获取当前进程名
        String processName = getProcessName(android.os.Process.myPid());
        // 设置是否为上报进程
        CrashReport.UserStrategy strategy = new CrashReport.UserStrategy(context);
        strategy.setUploadProcess(processName == null || processName.equals(packageName));
        // 初始化Bugly
        CrashReport.initCrashReport(context, BUGLY_ID, false, strategy);

    }
    /**
     * 获取进程号对应的进程名
     *
     * @param pid 进程号
     * @return 进程名
     */
    private static String getProcessName(int pid) {
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new FileReader("/proc/" + pid + "/cmdline"));
            String processName = reader.readLine();
            if (!TextUtils.isEmpty(processName)) {
                processName = processName.trim();
            }
            return processName;
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        } finally {
            try {
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException exception) {
                exception.printStackTrace();
            }
        }
        return null;
    }
    private void startPolling() {
        PollingUtils.startPollingService(this, 4000, PollingService.class, PollingService.ACTION);
    }

    private void initDisplayOpinion() {
        DisplayMetrics dm = getResources().getDisplayMetrics();
        DisplayUtil.density = dm.density;
        DisplayUtil.densityDPI = dm.densityDpi;
        DisplayUtil.screenWidthPx = dm.widthPixels;
        DisplayUtil.screenhightPx = dm.heightPixels;
        DisplayUtil.screenWidthDip = DisplayUtil.px2dip(getApplicationContext(), dm.widthPixels);
        DisplayUtil.screenHightDip = DisplayUtil.px2dip(getApplicationContext(), dm.heightPixels);
    }

    private void initSpeech() {
        SpeechUtility.createUtility(mAppContext, SpeechConstant.APPID +"=599aa631");
    }

    public static Context getAppContext() {
        return mAppContext;
    }

}
